package jpb.Interceptor;

import jpb.constant.StatusCode;
import jpb.module.daomain.member.Member;
import jpb.module.service.member.MemberService;
import jpb.security.HandleCookie;
import jpb.security.HandleToken;
import jpb.security.ProduceJwt;
import jpb.util.DateFormatUtil;
import jpb.util.NetworkUtil;
import jpb.util.XmlUtil;
import org.apache.catalina.connector.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by haol on 2017/4/20.
 */
public class AppLoginInterceptor extends HandlerInterceptorAdapter {
        private MemberService memberService;
        public AppLoginInterceptor(MemberService memberService){
                this.memberService = memberService;
        }
        Logger logger = LoggerFactory.getLogger(AppLoginInterceptor.class);
        HandleToken handleJWT = new HandleToken();
        private ProduceJwt produceJwt = new ProduceJwt();
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) throws Exception {

                boolean tokenLegal;
                //logger.info("进入验证APP Login拦截器");
                try {
                        /*测试用*/
                        if (XmlUtil.getStrByNode("appTest").equals("yes")){
                                logger.info("用户[{}]的访问路径为-->{}", "TEST",request.getRequestURI());
                                long nowMillis = System.currentTimeMillis();
                                Date nowTime = new Date(nowMillis);
                                Member member = memberService.get("201430098009");
                                String subject = handleJWT.generalSubject(member);
                                String jwt = produceJwt.produceAppToken(StatusCode.JWT_ID, subject, StatusCode.JWT_APP_TTL, nowTime);
                                logger.info(jwt);
                                HandleCookie.saveCookie(response, StatusCode.COOKIE_JWT_APP, jwt);
                                memberService.updateLoginTime(member.getMemberNum(), nowTime);

                               return true;
                        }

                        String token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_APP);
                        String num = handleJWT.getValueByKey(token, StatusCode.SUBJECT_KEY);

                        logger.info("用户[{}]的访问路径为-->{}", num,request.getRequestURI());

                        tokenLegal = handleJWT.analyzeJWT(token);

                        if (tokenLegal) {

                                  //判断登陆时间和jwt签发时间是否一致，实现单点登陆
                                Date date = handleJWT.getIssuedAt(token);

                                Member member = memberService.getLog(num);

                                if (date.getTime() != member.getLoginTime().getTime()) {
                                        logger.error("用户[{}]当前的IP地址为[{}],[{}]已在其他地方登录", member.getMemberNum(),NetworkUtil.getIpAddress(request),
                                                DateFormatUtil.getYMd(new Date(member.getLoginTime().getTime())));
                                        response.setStatus(Response.SC_UNAUTHORIZED);
                                        return false;
                                }

                        } else {
                                response.setStatus(Response.SC_UNAUTHORIZED);
                        }
                        return tokenLegal;

                } catch (NullPointerException e) {
                        logger.info("当前用户信息不存在，请重新登录");
                        response.setStatus(Response.SC_UNAUTHORIZED);
                        return false;
                }
        }

}
